package com.chengzhi.netty.client;

import com.chengzhi.netty.handler.ClientHandler;
import com.chengzhi.nettycommoms.codec.MarshallingCodeCFactory;
import com.chengzhi.nettycommoms.dto.NettyMessage;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NettyClient {

    private Channel CHANNEL;

    public NettyClient() {
        init("127.0.0.1", 9000);
    }

    private NioEventLoopGroup workGroup = new NioEventLoopGroup();
    private ChannelFuture channelFuture;

    private void init(String host, int port) {
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.group(workGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel channel) throws Exception {
                            channel.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
                            channel.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
                            channel.pipeline().addLast(new ClientHandler());
                        }
                    });
            channelFuture = bootstrap.connect(host, port).sync();
            CHANNEL = channelFuture.channel();
        } catch (Throwable throwable) {
            log.error("netty client init error", throwable);
        }
    }

    public void close() {
        try {
            channelFuture.channel().closeFuture().sync();
            workGroup.shutdownGracefully();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void sendMessage() {
        for (int i = 0; i < 10; i++) {
            NettyMessage nettyMessage = new NettyMessage();
            nettyMessage.setId((long) i);
            nettyMessage.setMsg("client id --------" + i);
            this.CHANNEL.writeAndFlush(nettyMessage);
        }
    }
}
